from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from .core.database import engine, Base, SessionLocal
from .routers import auth_router, departments_router, employees_router, projects_router, tasks_router, attendance_router, users_router, module_router
from .core.ensure_admin_only import ensure_admin_only_superuser
from .core.init_modules import init_modules

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 确保只有admin是超级用户
db = SessionLocal()
try:
    ensure_admin_only_superuser(db)
    # 初始化模块数据
    init_modules(db)
finally:
    db.close()

app = FastAPI(
    title="企业管理系统",
    description="企业管理系统后端API",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该配置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置静态文件服务
app.mount("/static", StaticFiles(directory="../frontend"), name="static")

# 注册路由
app.include_router(auth_router)
app.include_router(departments_router)
app.include_router(employees_router)
app.include_router(users_router)
app.include_router(projects_router)
app.include_router(tasks_router)
app.include_router(attendance_router)
app.include_router(module_router)

@app.get("/")
def read_root():
    return FileResponse("../frontend/index.html")

@app.get("/health")
def health_check():
    return {"status": "healthy"}